package com.zy.cat.common.utils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.TbkActivitylinkGetRequest;
import com.taobao.api.request.TbkDgOptimusMaterialRequest;
//import com.taobao.api.request.TbkDgVegasTljCreateRequest;
//import com.taobao.api.request.TbkDgVegasTljInstanceReportRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkJuTqgGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.request.TbkUatmFavoritesGetRequest;
import com.taobao.api.request.TbkUatmFavoritesItemGetRequest;
import com.taobao.api.response.TbkActivitylinkGetResponse;
import com.taobao.api.response.TbkDgOptimusMaterialResponse;
import com.taobao.api.response.TbkDgOptimusMaterialResponse.WordMapData;
//import com.taobao.api.response.TbkDgVegasTljCreateResponse;
//import com.taobao.api.response.TbkDgVegasTljCreateResponse.RightsInstanceCreateResult;
//import com.taobao.api.response.TbkDgVegasTljInstanceReportResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkJuTqgGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import com.taobao.api.response.TbkUatmFavoritesGetResponse;
import com.taobao.api.response.TbkUatmFavoritesItemGetResponse;
import com.zy.cat.entity.mall.resp.TKSelectionResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.entity.tb.resp.TKMaterialResp;
import com.zy.cat.entity.tb.resp.TKTQGResp;
 

import lombok.extern.slf4j.Slf4j;

/**
 * 淘宝接口
 * 
 * @author Link
 * @date 2019-06-27 11:43
 */
@Slf4j
public class TBAPI {

	public static final int DEFAULT_TYPE = 10;
	private final String url = "https://eco.taobao.com/router/rest";
	private String appkey = "28121056";
	private String secret = "6357fff5b950316c31498ef845aa9f2b";
	private String pid = "mm_127127112_1057200437_109739900432";
	private String inviterCode = "V5B2HP";
	private long adzonid = 130622567L;

	private TBAPI(String appkey, String secret, String pid, String inviterCode, long adzonid) {
		super();
		this.appkey = appkey;
		this.secret = secret;
		this.pid = pid;
		this.inviterCode = inviterCode;
		this.adzonid = adzonid;
	}

	/**
	 * 获取不同账户的api
	 * 
	 * @author Link
	 * @date 2019-06-27 14:01
	 * @param type 10.九趣猫安卓专用、11.九趣猫IOS专用
	 * @return
	 */
	public static TBAPI getInstance(int type) {
		String appkey = "25650123";
		String secret = "1916f2cbd3354d56be0f822f349692c6";
		String pid = "mm_621244881_35672161_130622567";
		String inviterCode = "V5B2HP";
		long adzonid = 130622567L;

		if (type == 1) {
			appkey = "26032814";
			secret = "30ea879a0be62f192d07ad218d9ea2bb";
			pid = "mm_359360108_426650050_109083950159";
			inviterCode = "NGYU9I";
			adzonid = 109083950159L;
		} else if (type == 10) {
			appkey = "28121056";
			secret = "6357fff5b950316c31498ef845aa9f2b";
			pid = "mm_127127112_1057200437_109739900432";
			adzonid = 109739900432L;
			inviterCode = "AB7EUP";
		} else if (type == 11) {
			appkey = "28121056";
			secret = "6357fff5b950316c31498ef845aa9f2b";
			pid = "mm_127127112_1057200437_109777600377";
			adzonid = 109777600377L;
			inviterCode = "AB7EUP";
		}else if (type == 20) {
			appkey = "29302482";
			secret = "4d90eaa3d2a165a31d57ead1fafa63ab";
			pid = "mm_127127112_1520400456_110383000089";
			inviterCode = "AB7EUP";
		}else if (type == 21) {
			appkey = "29302482";
			secret = "4d90eaa3d2a165a31d57ead1fafa63ab";
			pid = "mm_127127112_1520400456_110383000089";
			inviterCode = "AB7EUP";
		}else if (type == 30) {
			appkey = "29515689";
			secret = "e4059232968c98a1634651b93f5d0e45";
			pid = "mm_127127112_1663200385_110379750122";
			inviterCode = "AB7EUP";
		}else if (type == 31) {
			appkey = "29515689";
			secret = "e4059232968c98a1634651b93f5d0e45";
			pid = "mm_127127112_1663200385_110379750122";
			inviterCode = "AB7EUP";
		}
		return new TBAPI(appkey, secret, pid, inviterCode, adzonid);
	}

	public TbkUatmFavoritesGetResponse getTbkFavorites() {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkUatmFavoritesGetRequest req = new TbkUatmFavoritesGetRequest();
		req.setPageNo(1L);
		req.setPageSize(20L);
		req.setFields("favorites_title,favorites_id,type");
		req.setType(1L);
		TbkUatmFavoritesGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
//		System.out.println(rsp.getBody());
		return rsp;
	}

	public TbkUatmFavoritesItemGetResponse getTbkFavoritesShops() {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkUatmFavoritesItemGetRequest req = new TbkUatmFavoritesItemGetRequest();
		req.setPlatform(1L);
		req.setPageSize(20L);
		req.setAdzoneId(34567L);
		req.setUnid("3456");
		req.setFavoritesId(10010L);
		req.setPageNo(2L);
		req.setFields(
				"num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status,type");
		TbkUatmFavoritesItemGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
//		System.out.println(rsp.getBody());
		return rsp;
	}

	/**
	 * 
	 * @info 官方活动转链
	 * @author Link
	 * @date 2019-10-22 14:22
	 * @param rid 渠道关系ID，仅适用于渠道推广场景
	 * @param hid 官方活动ID，从官方活动页获取
	 * @return
	 */
	public String getTbkActivitylink(String rid, long hid) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkActivitylinkGetRequest req = new TbkActivitylinkGetRequest();
		req.setPlatform(2L);
		req.setUnionId("act_convert");
		req.setAdzoneId(this.adzonid);
		req.setPromotionSceneId(hid);
//		req.setSubPid("mm_123_123_123");
		req.setRelationId(rid);
		TbkActivitylinkGetResponse rsp;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			log.error("活动转链-ERROR-->{}", e.getLocalizedMessage());
			return null;
		}
		if (rsp != null && !StringUtils.isEmpty(rsp.getData())) {
			return rsp.getData();
		}
		return null;
	}

	/**
	 * 获取选品库列表
	 * 
	 * @return
	 */
	public TbkUatmFavoritesGetResponse getTbkUatmFavorites(Pages pages) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkUatmFavoritesGetRequest req = new TbkUatmFavoritesGetRequest();
		if (pages != null) {
			req.setPageNo(Long.valueOf(pages.getPageNum()));
			req.setPageSize(Long.valueOf(pages.getPageSize()));
		}
		req.setFields("favorites_title,favorites_id,type");
//		req.setType(1L);
		TbkUatmFavoritesGetResponse rsp = null;
		try {
			rsp = client.execute(req);
			System.out.println(rsp.getBody());
		} catch (ApiException e) {
			log.error("获取选品库列表异常:" + e.getMessage());
			e.printStackTrace();
		}
		return rsp;
	}

	/**
	 * 获取选品库商品信息
	 * 
	 * @param favoritesId 选品库ID
	 * @param pages       分页入参
	 * @return ResultPage<TKSelectionResp>
	 */
	public ResultPage<TKSelectionResp> getTbkUatmFavoritesItem(Long favoritesId, Pages pages) {
		ResultPage<TKMaterialResp> resultPage = getTbkDgOptimusMaterial((long)31539, "", favoritesId+"", pages);
		if (resultPage!=null && resultPage.getList()!=null) {
			List<TKSelectionResp> list = JSON.parseArray(JSON.toJSONString(resultPage.getList()),TKSelectionResp.class);
			List<TKMaterialResp> list2 = resultPage.getList();
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setNumIid(list2.get(i).getItemId()+"");
				if (list.get(i).getPictUrl().startsWith("//")) {
					list.get(i).setPictUrl("https:"+list.get(i).getPictUrl());
				}
				double lowLimit=0;
				if (list2.get(i).getCouponAmount()!=null) {
					if (StringUtils.isEmpty(list2.get(i).getCouponInfo()) && list2.get(i).getCouponInfo().contains("减")) {
						String limitStr=list2.get(i).getCouponInfo().substring(1, list2.get(i).getCouponInfo().indexOf("减"));
						if (StringUtils.isEmpty(limitStr)) {
							lowLimit=Double.parseDouble(limitStr);
						}
					}
					
				}
				double fianalPrice = Double.parseDouble(list2.get(i).getZkFinalPrice());
				if (fianalPrice>=lowLimit) {
					list.get(i).setActualPrice((fianalPrice-lowLimit)+"");	
				}
				list.get(i).setStatus(1);
			}
			
			ResultPage<TKSelectionResp> pageResult=new ResultPage<>(resultPage.getPageNum(), resultPage.getPageSize());
			pageResult.setTotal(pageResult.getTotal());
			pageResult.setList(list);
			return pageResult;
		}
		return null;
	}

	/**
	 * 物料精选
	 * 
	 * @param materialId 物料id，大额券综合：9660，高佣榜综合：13366
	 * @param deviceType 设备号类型：IMEI，或者IDFA
	 * @param pages      分页参数
	 * @return
	 */
	public ResultPage<TKMaterialResp> getTbkDgOptimusMaterial(Long materialId, String deviceType,String favoritesId, Pages pages) {
		//1. 创建请求淘宝数据对象
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		
		//2. 创建请求参数对象，设置请求参数
		TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
		if (pages != null) {
			req.setPageSize(Long.valueOf(pages.getPageSize()));
			req.setPageNo(Long.valueOf(pages.getPageNum()));
		}
		req.setAdzoneId(this.adzonid);
		req.setMaterialId(materialId);
//		req.setDeviceValue("xxx");
//		req.setDeviceEncrypt("MD5");
		req.setDeviceType(deviceType);
		req.setFavoritesId(favoritesId);
//		req.setContentId(323L);
//		req.setContentSource("xxx");
//		req.setItemId(33243L);
		
		//3. 创建响应返回数据类型对象，接收请求返回数据
		TbkDgOptimusMaterialResponse rsp = null;
		try {
			//执行请求
			rsp = client.execute(req);
			log.info(rsp.getBody());
			JSONObject jsonObject = JSON.parseObject(rsp.getBody());
			JSONObject errorRsp = jsonObject.getJSONObject("error_response");
			//判断请求是否异常，(判断错误json对象信息是否为空)
			if (errorRsp != null) {
				log.error("获取选品库商品信息异常:" + errorRsp.getString("sub_msg"));
				return null;
			}
			//4. 解析响应数据，数据商品列表
			JSONObject jsonObjectData = jsonObject.getJSONObject("tbk_dg_optimus_material_response");
			String listJson = jsonObjectData.getJSONObject("result_list").getString("map_data");
			//4.1 将获取到的商品数据转成list集合
			List<TKMaterialResp> list = JSON.parseArray(listJson, TKMaterialResp.class);
			//4.2 将商品集合转成json数组,用于计算佣金
			JSONArray parseArray = JSON.parseArray(listJson);
			//处理失效商品集合
			List<TKMaterialResp> removeList =new ArrayList<>(); 
			
			//5. 遍历json数据，设置商品图片与商品返利佣金
			for (int i = 0; i < parseArray.size(); i++) {
				TKMaterialResp obj = list.get(i);
				// 解析集合对象
				if (obj.getSmallImages() != null && obj.getSmallImages().size() > 0) {
					String string = JSON.parseObject(obj.getSmallImages().get(0)).getString("string");
					List<String> images = JSON.parseArray(string, String.class);
					obj.setSmallImages(images);
				}
				if (parseArray.getJSONObject(i).getJSONObject("word_list") != null) {
					String wordMapData = parseArray.getJSONObject(i).getJSONObject("word_list")
							.getString("word_map_data");
					List<WordMapData> wordList = JSON.parseArray(wordMapData, WordMapData.class);
					obj.setWordList(wordList);
				}
				// 计算返利金额
				double couponAmount = obj.getCouponAmount();
				if (StringUtils.isEmpty(obj.getZkFinalPrice())) {
					removeList.add(obj);
					continue;
				}
				double payAmount = Double.parseDouble(obj.getZkFinalPrice());
				double commissionRate = Double.parseDouble(parseArray.getJSONObject(i).getString("commission_rate"));
				obj.setFcode(CalculateUtil.getRebateAmount(payAmount, couponAmount, commissionRate));
			}
			
			//删除已失效商品
			list.removeAll(removeList);
			
			//6. 封装返回的数据
			ResultPage<TKMaterialResp> resultPage = new ResultPage<>();
			resultPage.setList(list);
			if (pages != null) {
				resultPage.setPageNum(pages.getPageNum());
				resultPage.setPageSize(pages.getPageSize());
			}
			return resultPage;
		} catch (ApiException e) {
			log.error("获取物料精选异常:" + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @info 淘抢购
	 * @author Link
	 * @date 2019-11-13 11:33
	 * @param stime    最早开团时间 2019-11-13 10:00:00
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<TKTQGResp> getTbkJuTqg(String stime, long page, long pageSize) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkJuTqgGetRequest req = new TbkJuTqgGetRequest();
		req.setAdzoneId(this.adzonid);
		req.setFields("pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,start_time,end_time");
		req.setStartTime(StringUtils.parseDateTime(stime));
		req.setEndTime(StringUtils.parseDateTime(
				TJKUtils.parse2LocalDateTime(stime).plusMinutes(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS)));
		req.setPageNo(page);
		req.setPageSize(pageSize);
		TbkJuTqgGetResponse rsp = null;
		try {
			rsp = client.execute(req);
			JSONObject jsonObject = JSON.parseObject(rsp.getBody());
			JSONObject errorRsp = jsonObject.getJSONObject("error_response");
			if (errorRsp != null) {
				log.error("获取选品库商品信息异常:" + errorRsp.getString("sub_msg"));
				return null;
			}
			JSONObject jsonObjectData = jsonObject.getJSONObject("tbk_ju_tqg_get_response");
			if (jsonObjectData.getJSONObject("results") == null) {
				return null;
			}
			String listJson = jsonObjectData.getJSONObject("results").getString("results");
			List<TKTQGResp> list = JSON.parseArray(listJson, TKTQGResp.class);
			return list;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getTbkItemInfo(String numIids) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
		req.setNumIids(numIids);
		req.setPlatform(2L);
		TbkItemInfoGetResponse rsp = null;
		try {
			rsp = client.execute(req);
			log.info("-getTbkItemInfo-->" + rsp.getBody());
			JSONObject jsonObject = JSON.parseObject(rsp.getBody());
			JSONObject errorRsp = jsonObject.getJSONObject("error_response");
			if (errorRsp != null) {
				log.error("获取选品库商品信息异常:" + errorRsp.getString("sub_msg"));
				return null;
			}
			JSONObject jsonObject2 = JSON.parseObject(rsp.getBody()).getJSONObject("tbk_item_info_get_response").getJSONObject("results");
			if (jsonObject2.containsKey("n_tbk_item") && jsonObject2.getJSONArray("n_tbk_item").size()>0) {
				return jsonObject2.getJSONArray("n_tbk_item").getString(0);
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取淘口令
	 * @info 
	 * @author Link
	 * @date 2020-06-17 17:15
	 * @param title
	 * @param uurl
	 * @return
	 */
	public String getTKL(String title,String uurl) {
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
//		req.setUserId("123");
		req.setText(title);
		req.setUrl(uurl);
//		req.setLogo("https://uland.taobao.com/");
//		req.setExt("{}");
		TbkTpwdCreateResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		log.info("--淘口令->{}",JSON.toJSONString(rsp.getBody()));
		if(rsp.getData()!=null&&!StringUtils.isEmpty(rsp.getData().getModel())) {
			return rsp.getData().getModel();
		}
		return null;
	}
	 
	
	
	


//	/**
//	 *
//	 * @info 获取淘礼金商品，转链
//	 * @author Link
//	 * @date 2020-06-17 09:44
//	 * @param sid	商品ID
//	 * @param perface	淘礼金价值20.99
//	 * @param days	领取过期时间（天）
//	 * @return
//	 */
//	public TbkDgVegasTljCreateResponse getTLJGoodsConvert(long sid,String perface,int days) {
//		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
//		TbkDgVegasTljCreateRequest req = new TbkDgVegasTljCreateRequest();
//		days=days<1?1:days;
//		req.setAdzoneId(adzonid);
//		req.setItemId(sid);
//		req.setTotalNum(1L);
//		req.setName("淘礼金来啦");
//		req.setUserTotalWinNumLimit(1L);
//		req.setSecuritySwitch(true);
//		req.setPerFace(perface);
//
//		req.setSendStartTime(StringUtils.parseDateTime(TJKUtils.DateTime()));
//		req.setSendEndTime(StringUtils.parseDateTime(LocalDateTime.now().plusHours(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS)));
//
//		req.setUseEndTimeMode(1L);
//		req.setUseEndTime("1");
//		TbkDgVegasTljCreateResponse rsp = null;
//		try {
//			rsp = client.execute(req);
//		} catch (ApiException e) {
//			e.printStackTrace();
//		}
// 		log.info("--淘礼金->{}",JSON.toJSONString(rsp.getBody()));
//		return rsp;
//	}
	
	public static void main(String[] args) throws ParseException {
		long sid=619634407653l;
		TBAPI instance = getInstance(10);
//		TbkDgVegasTljCreateResponse result=instance.getTLJGoodsConvert(sid, "1", 1);
		
//		instance.getTKL("淘礼金来啦",result.getResult().getModel().getSendUrl());
 
//		log.info("--getMsgCode->{}",result.getResult().getMsgCode());
//		log.info("--getMsgInfo->{}",result.getResult().getMsgInfo());
		ResultPage<TKSelectionResp> item = instance.getTbkUatmFavoritesItem(2015611021l, new Pages(1, 10));
		System.out.println(JSON.toJSONString(item));
		
		
//		ResultPage<TKMaterialResp> resultPage = instance.getTbkDgOptimusMaterial((long)25888, "", "", new Pages(1, 10));
//		List<TKSelectionResp> list = JSON.parseArray(JSON.toJSONString(resultPage.getList()),TKSelectionResp.class);
//		System.out.println(JSON.toJSONString(resultPage));
	}
}
